<?php

namespace Dreamcat\ConfigClient\Impl\Saver;

use Components\Utils\Funcs\FileSystemHelper;
use Dreamcat\ConfigClient\ConfigSaverInterface;
use Dreamcat\ConfigClient\Popo\ConfigResult;
use RuntimeException;

/**
 * sugarcrm保存器
 * @author vijay
 */
class SugarCrmSaver implements ConfigSaverInterface
{
    /** @var string 配置文件目录 */
    private $configDir;

    /**
     * SugarCrmSaver constructor.
     * @param string $configDir 配置文件目录
     */
    public function __construct(string $configDir)
    {
        if (!FileSystemHelper::mkdir($configDir)) {
            throw new RuntimeException("配置文件 {$configDir} 无法创建");
        }
        $this->configDir = $configDir;
    }

    /**
     * @inheritDoc
     */
    public function saveConfig(ConfigResult $configResult): bool
    {
        $key = md5(json_encode($configResult->getAppInfo()));
        $configs = $configResult->getConfigurations();
        $time = date("Y-m-d H:i:s");
        $code = $this->exportVar2String($configs, "sugar_config");
        $code = <<<CODE
<?php
# 在 {$time} 由配置中心客户端生成的配置文件

{$code}

# end of file

CODE;
        return file_put_contents("{$this->configDir}/{$key}.php", $code);
    }

    private function exportVar2String($config, $name, $prefix = ""): string
    {
        $code = "";
        foreach ($config as $key => $val) {
            $full = "{$prefix}[" . var_export($key, true) . "]";
            if (is_array($val)) {
                $code .= $this->exportVar2String($val, $name, $full);
            } else {
                $code .= "\${$name}{$full} = " . var_export($val, true) . ";\n";
            }
        }
        return $code;
    }

    /**
     * @inheritDoc
     */
    public function onSaveAll(): void
    {
    }
}

# end of file
